import { Injectable } from '@nestjs/common';
import { CreateDictDto } from './dto/create-dict.dto';
import { UpdateDictDto } from './dto/update-dict.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { Dict } from './entities/dict.entity';

@Injectable()
export class DictService {
  constructor(
    @InjectRepository(Dict)
    private readonly dictRepository: Repository<Dict>,
  ) {}
  async create(createDictDto: CreateDictDto) {
    const tempDict = await this.dictRepository.create(createDictDto);
    return this.dictRepository.save(tempDict);
  }

  async findAll(body) {
    const { pageSize = 10, pageNum = 1, ...params } = body;
    console.log('body', body, params);

    const dict = this.dictRepository.createQueryBuilder('dict');
    for (const key in params) {
      if (params[key]) {
        dict.where(`dict.${key} LIKE :${key}`, { [key]: `%${params[key]}%` });
      }
    }
    const result = await dict
      .skip((pageNum - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    return {
      rows: result[0],
      total: result[1],
    };
  }
  async findDict(query) {
    const codes = query.split(',');
    const dict = await this.dictRepository.find({
      where: { code: In(codes) },
      select: ['items', 'code'],
    });
    const result = {};
    dict.forEach((res) => {
      result[res.code] = res.items;
    });
    return result;
  }
  findOne(id: number) {
    return this.dictRepository.findOne({ where: { id: id } });
  }

  async update(updateDictDto) {
    const { id, ...params } = updateDictDto;
    this.dictRepository.update(id, params);
    return '更新成功';
  }

  remove(ids: string) {
    ids.split(',').map((id) => {
      this.dictRepository.delete(id);
    });
    return '删除成功';
  }
}
